package com.leyou.web;

import com.leyou.common.vo.PageResult;
import com.leyou.mapper.SpuDetailMapper;
import com.leyou.pojo.Sku;
import com.leyou.pojo.Spu;
import com.leyou.pojo.SpuDetail;
import com.leyou.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class GoodsController {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private SpuDetailMapper spuDetailMapper;

    @GetMapping("/spu/page")
    public ResponseEntity<PageResult<Spu>> queryByPage(
            @RequestParam(value = "page",defaultValue = "1") Integer page,
            @RequestParam(value = "rows",defaultValue = "5") Integer rows,
            @RequestParam(value = "saleable",required = false) Boolean saleable,
            @RequestParam(value = "key",required = false) String key
    ){
        return  ResponseEntity.ok(goodsService.queryByPage(page,rows,saleable,key));
    }

    @PostMapping("goods")
    public ResponseEntity<Void> saveGoods(@RequestBody Spu spu){
        goodsService.saveGoods(spu);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @GetMapping("/spu/detail/{id}")
    public ResponseEntity<SpuDetail> querySpuDetailById(@PathVariable("id") Long id) {
        SpuDetail detail = spuDetailMapper.selectByPrimaryKey(id);
        if (detail == null) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(detail);
    }

    @GetMapping("sku/list")
    public ResponseEntity<List<Sku>> querySkuBySpuId(@RequestParam("id") Long id) {
        List<Sku> skus = this.goodsService.querySkuBySpuId(id);
        if (skus == null || skus.size() == 0) {
            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
        }
        return ResponseEntity.ok(skus);
    }

    @GetMapping("/spu/{id}")
    public  ResponseEntity<Spu> getSpuById(@PathVariable("id") Long id){
        return ResponseEntity.ok(goodsService.getSpuById(id));
    }

    @PostMapping("decrease")
    public ResponseEntity<Void>  decrease(@RequestParam("id") Long id){
        goodsService.decrease(id);
        return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
    }

 }
